/**
 * @author Klaoye
 * @license Apache 2.0 设置存储类
 */

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.HashMap;

public class Settings {
	static final File settings_file = new File("settings.json");/* 设置存储文件 */
	public static HashMap<String, Object> setting_map = new HashMap<>();/* 存储设置哈希图 */
	public static final String default_regular_expression = "([\n\r])([ 正文第☆]+)([1234567890一二三四五六七八九十零千百万]+)([章回集])([^\n\r]+)([\n\r])|"
			+ "([正文第]+)([1234567890一二三四五六七八九十零千百万]+)([章回集])([\n\r])|"
			+ "([\n\r])([*☆★○●◎◇◆□■△▲、. 　]+)([1234567890一二三四五六七八九十零]+)([\n\r])|"
			+ "([\n\r])([.．])([1234567890]+)([^\n\r]+)([\n\r])";

	public static void init() {// 初始化函数建议首先执行
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		if (!settings_file.exists()) {// 设置文件是否存在
			makeDefaultSettings();
			FileOperator.writeFile(settings_file, gson.toJson(setting_map));// 写入设置文件
		} else {
			try {
				setting_map = gson.fromJson(FileOperator.readFile(settings_file), HashMap.class);
				// 反序列化（读取设置文件）JSON->对象
			} catch (IOException e) {
				e.printStackTrace();
				makeDefaultSettings();
			}
		}
		Runtime.getRuntime().addShutdownHook(new Thread(Settings::apply));// 退出时执行保存
	}

	/**
	 * 序列化（存储设置）对象->JSON
	 */
	public static void apply() {// 保存函数
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		boolean b = FileOperator.writeFile(settings_file, gson.toJson(setting_map, HashMap.class));
	}

	private static void makeDefaultSettings() {// 设置默认设定
		String defaultCharset = Charset.defaultCharset().name();
		String default_expression;
		try {
			default_expression = new String(default_regular_expression.getBytes(), defaultCharset);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			default_expression = default_regular_expression;
		}
		setting_map.put("color_style", ColorStyle.WRITE);
		setting_map.put("regular_expression", default_expression);
		setting_map.put("last_open", FileSystemView.getFileSystemView().getHomeDirectory().toString());
		setting_map.put("book_map", new HashMap<>());
	}

}
